package edu.uni.dormitory.controller;

import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.dormitory.bean.ExchangeApply;
import edu.uni.dormitory.bean.RoomExchange;
import edu.uni.dormitory.globalbean.ExchangeVo;
import edu.uni.dormitory.globalbean.BedVo;
import edu.uni.dormitory.service.BedService;
import edu.uni.dormitory.service.ExchangeService;
import edu.uni.example.config.ExampleConfig;
import edu.uni.userBaseInfo1.bean.Employee;
import edu.uni.userBaseInfo1.service.EmployeeService;
import edu.uni.userBaseInfo1.service.StudentService;
import edu.uni.userBaseInfo1.service.UserService;
import edu.uni.dormitory.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

import static edu.uni.bean.ResultType.*;

/**
 * 调换宿舍
 */
@Api(description = "调换宿舍模块")
@RestController
@RequestMapping("json/dorm/exchange")
public class ExchangeController{

    @Autowired
    private ExchangeService exchangeService;
    @Autowired
    private ExampleConfig globalConfig;

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private BedService bedService;
    @Autowired
    private AuthService authService;
    /**
     * 通过主键获取某条换宿舍记录
     */
    @ApiOperation(value = "通过主键获取某条换宿舍记录", notes = "")
    @GetMapping("{id}")
    public Result receiveExchangeById(@PathVariable("id")Long id,HttpSession session){
        System.out.println(id);
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能获取的权限
            ExchangeApply exchangeApply=null;
            //学生
            if(isHasRole(roleList,"学生")){
                exchangeApply = exchangeService.selectExchangeApplyById(id, Long.valueOf(loginId));

            }//辅导员
            else if(isHasRole(roleList,"辅导员")){
                //最好是有缓存是哪个学院的辅导员
                Long collegeId = (Long) session.getAttribute("collegeId");
                if(collegeId == null){
                    List<Employee> employeeList = employeeService.selectByUserId(Long.valueOf(loginId));
                    long employeeId = (employeeList==null||employeeList.size()==0)?-1:employeeList.get(0).getId();
                    if(employeeId == -1) return Result.build(Failed);
                    collegeId = employeeService.selectEmployeeById(employeeId).getDepartmentId();
                }
                exchangeApply = exchangeService.selectExchangeApplyByIdWithInstructor(id, collegeId);
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
                exchangeApply = exchangeService.selectExchangeApplyById(id);
            }
            if(exchangeApply != null){
                String applyId = String.valueOf(exchangeApply.getId());
                String studentNo = studentService.selectById(exchangeApply.getApplyPerson()).getStuNo();
                String studentName = userService.selectUserById(exchangeApply.getByWho()).getUserName();
                String applyTime = DateUtil.date2string(exchangeApply.getApplyDate());
                String reason = exchangeApply.getReason();
                String status = exchangeService.selectExchangeStatusByApplyId(exchangeApply.getId());
//               交换前后的信息
                RoomExchange tmp = exchangeService.selectExchangeByApplyId(exchangeApply.getId());
                ExchangeVo exchangeVo;
                if(tmp != null){
                    BedVo beforeBed = bedService.selectByliveBedId(tmp.getBeforeBedId());
                    BedVo afterBed = bedService.selectByliveBedId(tmp.getAfterBedId());
                    exchangeVo = new ExchangeVo(applyId,studentName,studentNo,applyTime,reason,status,
                            beforeBed.getAreaName(),String.valueOf(beforeBed.getRoom()),String.valueOf(beforeBed.getNumber()),
                            afterBed.getAreaName(),String.valueOf(afterBed.getRoom()),String.valueOf(afterBed.getNumber()));
                }else {
                    exchangeVo = new ExchangeVo(applyId,studentName,studentNo,applyTime,reason,status,
                            null,null,null,
                            null,null,null);
                }
                return Result.build(Success).appendData("list",new ArrayList<ExchangeVo>(){{this.add(exchangeVo);}});
            }
        //缓存
        return Result.build(Failed);
    }
    /**
     * 获取换宿舍记录
     */
    @ApiOperation("分页获取换宿舍记录")
    @GetMapping("list")
    public Result listExchange(String areaId,Integer status,HttpSession session){
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
//        loginId = "101";loginRole="student";
        //todo 家长角色
//        loginId = "3";loginRole="familyHead";
        //todo 宿管中心角色
//        loginId = "4";loginRole="settlementCenter";
        //根据身份判断是否有能获取的权限
            List<ExchangeApply> exchangeApplyList=null;
            //学生
            if(isHasRole(roleList,"学生")){
                exchangeApplyList = exchangeService.selectExchangeApplyPageBySelf(Long.valueOf(loginId));
            }//辅导员
            else if(isHasRole(roleList,"辅导员")){
                //最好是有缓存是哪个学院的辅导员
                Long collegeId = (Long) session.getAttribute("collegeId");
                if(collegeId == null){
                    long employeeId =getEmploeeIdByUserId(Long.valueOf(loginId));
                    if(employeeId == -1) return Result.build(Failed);
                    collegeId = employeeService.selectEmployeeById(employeeId).getDepartmentId();
                }
                exchangeApplyList = exchangeService.selectExchangeApplyPageByCollege(collegeId);
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
//                exchangeApplyList = exchangeService.selectExchangeApplyPageByArea(Long.valueOf(areaId));
                exchangeApplyList = exchangeService.selectExchangeApplyList();
            }
            if(exchangeApplyList != null && exchangeApplyList.size()>0){
                List<ExchangeVo> exchangeVoList = new ArrayList<>();
                for(ExchangeApply apply:exchangeApplyList){
                    String applyId = String.valueOf(apply.getId());
                    String s = exchangeService.selectExchangeStatusByApplyId(apply.getId());
                    if(!judgeStatus(status,s,roleList)) continue;
                    String studentNo = studentService.selectById(apply.getApplyPerson()).getStuNo();
                    String studentName = userService.selectUserById(apply.getByWho()).getUserName();
                    String applyTime = DateUtil.date2string(apply.getApplyDate());
                    String reason = apply.getReason();
                    RoomExchange tmp = exchangeService.selectExchangeByApplyId(apply.getId());
                    if(tmp != null){
                        BedVo beforeBed = bedService.selectByliveBedId(tmp.getBeforeBedId());
                        BedVo afterBed = bedService.selectByliveBedId(tmp.getAfterBedId());
                        ExchangeVo exchangeVo = new ExchangeVo(applyId,studentName,studentNo,applyTime,reason,s,
                                beforeBed.getAreaName(),String.valueOf(beforeBed.getRoom()),String.valueOf(beforeBed.getNumber()),
                                afterBed.getAreaName(),String.valueOf(afterBed.getRoom()),String.valueOf(afterBed.getNumber()));
                        exchangeVoList.add(exchangeVo);
                    }else {
                        ExchangeVo exchangeVo = new ExchangeVo(applyId,studentName,studentNo,applyTime,reason,s,
                                null,null,null,
                                null,null,null);
                        exchangeVoList.add(exchangeVo);
                    }
                }
                return Result.build(Success).appendData("list", exchangeVoList);
            }
        //缓存
        return Result.build(Failed);
    }
    /**
     * 学生申请换宿舍
     */
    @ApiOperation("学生申请换宿舍")
    @PostMapping("")
    public Result insertExchange(ExchangeApply exchangeApply,HttpSession session){
        //获取登录人id、角色
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
            //学生
            if(isHasRole(roleList,"学生")){
                int i = exchangeService.insertExchangeApply(exchangeApply,Long.valueOf(loginId));
                if(i > 0){
                    return Result.build(Success);
                }
            }
            //其他人
        return Result.build(Failed);
    }
    /**
     * 审核换宿舍(根据缓存的角色来判断是辅导员还是宿管中心)
     */
    @ApiOperation("审核换宿舍(根据缓存的角色来判断是辅导员还是宿管中心)")
    @PostMapping("{id}")
    public Result checkExchange(@PathVariable("id")Long id,String agree,HttpSession session){
        //获取登录人id、角色
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
            int i = 0;
            //辅导员
            if(isHasRole(roleList,"辅导员")){
                i = exchangeService.updateExchangeApplyWithInstructor(id,Byte.valueOf(agree),Long.valueOf(loginId));
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
                i = exchangeService.updateExchangeApplyWithSettlementCenter(id,Byte.valueOf(agree),Long.valueOf(loginId));
            }
            //其他人
            if(i > 0 ){
                return Result.build(Success);
            }
        return Result.build(Failed);
    }
    private long getEmploeeIdByUserId(Long userId){
        List<Employee> employeeList = employeeService.selectByUserId(userId);
        return (employeeList==null||employeeList.size()==0)?-1:employeeList.get(0).getId();
    }

    private boolean judgeStatus(Integer status, String s, List<String> roleList){
        if(!"不同意".equals(s) && isHasRole(roleList,"辅导员")){
            if(0 == status && "辅导员确认中".equals(s)) return true;
            if(1 == status) {
                if( "宿管中心确认中".equals(s)|| "已完成".equals(s)){
                    return true;
                }
            }
        }else if(!"不同意".equals(s) && isHasRole(roleList,"宿管中心人员")){
            if(0 == status && "宿管中心确认中".equals(s)) return true;
            if(1 == status) {
                if("已完成".equals(s)){
                    return true;
                }
            }
        }else if(isHasRole(roleList,"学生")){
            return true;
        }
        return false;
    }

    private boolean isHasRole(List<String> roleList, String role) {
        for(String r:roleList){
            if(r.equals(role)){
                return true;
            }
        }
        return false;
    }
}
